
// let community = document.getElementById("community");
// community.innerHTML = vc.getCurrentCommunity().caName;
function _loadCOmmunity() {
  let param = {
    params: {
      caId: vc.getCurrentCommunity().caId,
      page: 1,
      row: 50
    }
  }
  vc.http.apiGet(
    '/govCommunity/queryGovCommunity',
    param,
    function (json, res) {
      //vm.menus = vm.refreshMenuActive(JSON.parse(json),0);
      let _json = JSON.parse(json);
      if (_json.code == 0) {
        let _data = _json.data;
        _data.forEach(comItem => {
          if (comItem.govCommunityAttrDtos.length > 0) {
            comItem.govCommunityAttrDtos.forEach(item => {
              if (item.specCd == 'map_x') {
                comItem.mapX = item.value;
              }
              if (item.specCd == 'map_y') {
                comItem.mapY = item.value;
              }
            });
          }
        });
        initMap(_data);
        return;
      }
    },
    function (errInfo, error) {
      console.log('请求失败处理');
      vc.toast(errInfo);

    });
}
function initMap(_data) {
  let _mapX = 116.397732;
  let _mapY = 39.912152;
  if (_data.length > 0) {
    _mapX = _data[0].mapX;
    _mapY = _data[0].mapY;
  }
  var map = new AMap.Map('oneMap', {
    viewMode: '3D',
    showBuildingBlock: false,
    center: [_mapX, _mapY],
    pitch: 55,
    zoom: 17
  })
  for (var p in _data) {
    var icon = new AMap.Icon({
      size: new AMap.Size(50, 50),    // 图标尺寸
      image: _data[p].communityIcon,  // Icon的图像
      imageSize: new AMap.Size(50, 50)
    });
    new AMap.Marker({
      title: _data[p].communityName,
      //icon: _data[p].communityIcon,
      icon: icon, // 添加 Icon 实例
      offset: new AMap.Pixel(-10, -10),
      position: [_data[p].mapX, _data[p].mapY],
      map: map,
    })
    new AMap.Text({
      text: _data[p].communityName,
      position: [_data[p].mapX, _data[p].mapY],
      height: 650,
      verticalAlign: 'bottom',
      map: map,
      style: {
        'color': "red",
        'border-color': 'white',
        'font-size': '18px'
      }
    })
  }


}

var machines = [];
var sipDatas = {};
var clientId = vc.uuid();
var websocketUrl = '';
function _listMachines() {
  let param = {
    params: {
      page: 1,
      row: 4,
      machineTypeCd: '9998',
      caId: vc.getCurrentCommunity().caId,
      isShow: 'Y'

    }
  }
  //发送get请求
  vc.http.apiGet('/machine/queryMachine',
    param,
    function (json, res) {
      let _machineManageInfo = JSON.parse(json);
      machines = _machineManageInfo.data;
      if (machines.length < 1) {
        return;
      }
      websocketUrl = machines[0].websocketUrl;
      let index = 1;
      machines.forEach(element => {
        _initMachineVideo('aleftboxt' + index, element.machineId, clientId);
        index = index + 1;
      });
      _initParkingAreaWs();
    }, function (errInfo, error) {
      console.log('请求失败处理');
    }
  );
}
function _initMachineVideo(_aleftboxt1, _machineId, _clientId) {
  if (!_machineId) {
    return;
  }
  console.log(_machineId);
  let param = {
    params: {
      page: 1,
      row: 4,
      caId: vc.getCurrentCommunity().caId,
      machineId: _machineId,
      clientId: _clientId
    }
  }
  //发送get请求
  vc.http.apiGet('/machine/checkMachine',
    param,
    function (json, res) {
      let _machineManageInfo = JSON.parse(json);
      sipDatas = _machineManageInfo;
      _playVideo(_aleftboxt1, sipDatas.url);
    }, function (errInfo, error) {
      console.log('请求失败处理');
    }
  );
}
function _playVideo(_videoId, url) {
  $('#' + _videoId).show();
  let sdk = null; // Global handler to do cleanup when replaying.
  sdk = new SrsRtcPlayerAsync();
  $('#' + _videoId).prop('srcObject', sdk.stream);
  sdk.play(url).then(function (session) {
  }).catch(function (reason) {
    sdk.close();
    $('#' + _videoId).hide();
    console.error(reason);
  });
}
function _initParkingAreaWs() {
  let heartCheck = {
    timeout: 30000,        // 9分钟发一次心跳，比server端设置的连接时间稍微小一点，在接近断开的情况下以通信的方式去重置连接时间。
    serverTimeoutObj: null,
    pingTime: new Date().getTime(),
    reset: function () {
      clearTimeout(this.serverTimeoutObj);
      return this;
    },
    start: function () {
      let self = this;
      this.serverTimeoutObj = setInterval(function () {
        if (websocket.readyState == 1) {
          console.log("连接状态，发送消息保持连接");
          let _pingTime = new Date().getTime();
          //保护，以防 异常
          if (_pingTime - self.pingTime < 15 * 1000) {
            return;
          }
          websocket.send("{'cmd':'ping'}");
          self.pingTime = _pingTime;

          heartCheck.reset().start();    // 如果获取到消息，说明连接是正常的，重置心跳检测
        } else {
          console.log("断开状态，尝试重连");
          $that._initParkingAreaWs();
        }
      }, this.timeout)
    }
  }

  let _protocol = window.location.protocol;
  let url = '';
  if (_protocol.startsWith('https')) {
    url =
      "wss://" + websocketUrl + "/ws/parkingArea/" + clientId;
  } else {
    url =
      "ws://" + websocketUrl + "/ws/parkingArea/" + clientId;
    // url =
    //     "ws://demo.homecommunity.cn:9011/ws/parkingArea/" +
    //     $that.parkingAreaControlInfo.boxId + "/" + clientId;
  }


  if ("WebSocket" in window) {
    websocket = new WebSocket(url);
  } else if ("MozWebSocket" in window) {
    websocket = new MozWebSocket(url);
  } else {
    websocket = new SockJS(url);
  }

  //连接发生错误的回调方法
  websocket.onerror = function (_err) {
    console.log("初始化失败", _err);
    this.$notify.error({
      title: "错误",
      message: "连接失败，请检查网络"
    });
  };

  //连接成功建立的回调方法
  websocket.onopen = function () {
    heartCheck.reset().start();
    websocket.send(JSON.stringify(machines));
    console.log("ws初始化成功");
  };
  //连接关闭的回调方法
  websocket.onclose = function () {
    console.log("初始化失败");
    //$that._initParkingAreaWs();
    this.$notify.error({
      title: "错误",
      message: "连接关闭，请刷新浏览器"
    });
  };
  //接收到消息的回调方法
  websocket.onmessage = function (event) {
    heartCheck.reset().start();
    console.log("event", event);
    let _data = event.data;
    try {
      _data = JSON.parse(_data);
    } catch (err) {
      return;
    }
  };
  //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
  window.onbeforeunload = function () {
    websocket.close();
  };
}
_loadCOmmunity();
_listMachines();